package com.yingxin.yx.framework.security.provider;

import com.yingxin.yx.framework.commons.constant.CommonConst;
import com.yingxin.yx.framework.commons.enums.PcOrAppEnums;
import com.yingxin.yx.framework.encrpty.rsa.RsaUtil;
import com.yingxin.yx.framework.security.pwd.Sha1PasswordEncoder;
import com.yingxin.yx.framework.security.user.PrincipalDto;
import com.yingxin.yx.framework.security.userdetails.AccountUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Component;

/**
 * 自定义登录验证
 */

@Component
public class AccountAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private AccountUserDetailsService accountUserDetailsService;

    @SuppressWarnings("rawtypes")
    @Autowired
    @Qualifier(value = "stringRedisTemplate")
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // 获取表单输入中返回的用户名
        String username = (String) authentication.getPrincipal();
        // 获取表单中输入的密码
        String password = (String) authentication.getCredentials();
        String plainPassword = RsaUtil.decryptByPrivateKey(password.trim());
        // 查询用户是否存在
        PrincipalDto principal = (PrincipalDto) accountUserDetailsService.loadUserByUsername(username);
        if (principal == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        if (CommonConst.TRUE.equals(principal.getFindByIdFlag())) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        if (plainPassword == null || !new Sha1PasswordEncoder().matches(plainPassword, principal.getPassword())) {
            WebAuthenticationDetails webAuthenticationDetails =
                    ( WebAuthenticationDetails ) authentication.getDetails();

            accountUserDetailsService.saveLoginErrorLog( username, plainPassword,
                    webAuthenticationDetails.getRemoteAddress(),
                    PcOrAppEnums.PC.getType() );

            throw new BadCredentialsException("用户名或密码错误");
        }

        /**
        // 校验证书是否有效
        LicenseVerifyManager licenseVerifyManager = new LicenseVerifyManager();
        LicenseResult verifyResult = licenseVerifyManager.verify(properties.getVerifyParam());
        if(!verifyResult.getResult()){
            throw new BadCredentialsException(verifyResult.getMessage());
        }
        */

        /*
        if (principal.getStatus().equals(CommonConst.TRUE)) {
            throw new LockedException("该用户已被冻结");
        }
        */
        /*
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (String permissionString : principal.getResourceSet()) {
            if (StringUtils.isNotEmpty(permissionString)) {
                authorities.add(new SimpleGrantedAuthority(permissionString));
            }
        }
        principal.setAuthorities(authorities);
        */
        return new UsernamePasswordAuthenticationToken(principal, plainPassword, principal.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return true;
    }

        /*
        SelfUserEntity userInfo = usersService.getUserInfo(userName);
        if (userInfo.getUsername() == null || userInfo.getUsername() == "") {
            throw new UsernameNotFoundException("用户名或密码错误");
        }


        // 我们还要判断密码是否正确，这里我们的密码使用BCryptPasswordEncoder进行加密的
        if (!new BCryptPasswordEncoder().matches(password, userInfo.getPassword())) {
            throw new BadCredentialsException("用户名或密码错误");
        }
        // 还可以加一些其他信息的判断，比如用户账号已停用等判断
        if (userInfo.getStatus().equals(CommonConst.TRUE)) {
            throw new LockedException("该用户已被冻结");
        }
        // 角色集合
        Set<GrantedAuthority> authorities = new HashSet<>();

        EntityWrapper<Usermeta> roleWrapper = new EntityWrapper<>();
        roleWrapper.eq("user_id",userInfo.getUserId());
        roleWrapper.eq("meta_key","wp_user_level");
        // 查询角色
        List<Usermeta> sysRoleEntityList = usermetaService.selectList(roleWrapper);
        for (Usermeta sysRoleEntity: sysRoleEntityList){
            authorities.add(new SimpleGrantedAuthority("ROLE_" + sysRoleEntity.getMetaValue()));
        }
        */

}